#include "task.hpp"
#include <unistd.h>
#include <string>
#include <vector>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>

const int processnum = 5;
//加载任务
std::vector<task> tasks;

//先描述
class channel
{
public:
    channel(int fd, pid_t id, std::string& process)
    :_cmdfd(fd), _slaverid(id), _processname(process)
    {}

    int _cmdfd;     //发送任务的文件描述符
    pid_t _slaverid; //子进程pid
    std::string _processname;  //子进程名字,方便打印日志
};

//等待任务
void slaver()
{
    while (true)
    {
        //std::cout << rfd << std::endl;
        //读到int再执行
        int cmdcode;
        ssize_t ret = read(3, &cmdcode, sizeof(int));
        if (ret == sizeof(int))
        {
            std::cout << getpid() << "收到任务: " << cmdcode << std::endl;
            if (cmdcode >= 0 && cmdcode < tasks.size())
            {
                 tasks[cmdcode]();
            }      
        }
        if (ret == 0)
        {
            //std::cout << "读到0退出";
            break;
        }
        sleep(1);
    }
}

void initpool(std::vector<channel>* v)
{
    std::vector<int> oldds;
    for (int i = 0; i < processnum; i++)
    {
        int pipefd[2];  //临时空间
        int n = pipe(pipefd);
        assert(!n);
       
        pid_t id = fork();
        if (id < 0)
        {
            return;
        }
        else if (id == 0)
        {
            for(auto ch : oldds)
            {
                //std::cout << "子进程补充关闭 " << ch;
                close(ch);
            }
            //printf("\n");
            // child
            close(pipefd[1]);
            //替换后从标准输入读取
            dup2(pipefd[0], 0);
            oldds.push_back(pipefd[0]);
            slaver();
           // std::cout << getpid() << "退出" << std::endl;
            exit(0);
        }

        close(pipefd[0]);

        //父类添加成员
        std::string str = "process: " + std::to_string(i);
        v->push_back(channel(pipefd[1], id, str));
        oldds.push_back(pipefd[1]);

    }
}

void menu()
{
    std::cout << "################################" << std::endl;
    std::cout << "##1.刷新野怪        2.刷新日志##" << std::endl;
    std::cout << "##3.检测更新        4.释放技能##" << std::endl;
    std::cout << "##0.退出                      ##" << std::endl;
    std::cout << "################################" << std::endl;

}

void crtlslaver(const std::vector<channel>& v)
{
    //int which = 0;
    menu();

    while (true)
    {
        int wid = 0;
        std::cin >> wid;
        if (wid <= 0 || wid > 4)
        {
            break;
        }
        // 选择任务,负载均衡,随机或轮询
       // int wid = rand() % tasks.size();
        // 选择进程
        int processpos = rand() % v.size();
        // 发送任务
        write(v[processpos]._cmdfd, &wid, sizeof(int));
        std::cout << "父进程给" << v[processpos]._slaverid << "发送" << wid << "号任务" << std::endl;
        sleep(1);
       // which++;
    }

}

void debug(const std::vector<channel>& v)
{
  for (auto& ch : v)
    {
        std::cout << ch._cmdfd << " " << ch._slaverid << " " << ch._processname << std::endl;
    }
}

void quitprocess(std::vector<channel>& v)
{
    for (auto ch : v)
    {
        close(ch._cmdfd);
        waitpid(ch._slaverid, nullptr, 0);
        // sleep(2);
    }
}

int main()
{
    //随机数种子
    srand(time(nullptr) ^ getpid() ^ 1023);  //位或更离散一点
    //加载任务
    loadtask(&tasks);
    // 再组织
    std::vector<channel> channels;
    //初始化
    //创建管道
    initpool(&channels);

    // 开始控制子进程
    // test
    // debug(v);
    crtlslaver(channels);
    // 清理
    quitprocess(channels);
   // sleep(5);

    return 0;
}
